library(foreign)
echrjud <- read.dta("BayesECtHRMasterData.dta")
summary(echrjud)

#Set working directory below
setwd("")
library(R2jags)


## Now define the vectors of the data matrix for JAGS:

echrJUD <- echrjud$numcaseimpk12jud_1
echrviol <- echrjud$numcase_impk12_1
jud_var <- echrjud$judpowervar_1
jud <- echrjud$lji_1
veto <- echrjud$polconiii_1
speech <- echrjud$speech_1
fdi <- echrjud$lfdi_1
cs <- echrjud$cs_1
nhri <- echrjud$nhri_1
exec <- echrjud$xrcomp_1
regionalcount <- echrjud$regionalcountimpk12bin_1
gdp <- echrjud$gdpcaplog_1
elections <- echrjud$v2xel_frefair_1
popmillions <- echrjud$popmillionslog_1
cwar <- echrjud$cwar_1
physint <- echrjud$repressionlatent
physint_var <- echrjud$repressionlatentvar
ccode <- echrjud$ccode
id <- echrjud$id
year <- echrjud$year

N <- length(echrjud$ccode)

## Read in the Courts data for JAGS

echrjud.data  <- list("id", "echrJUD", "echrviol", "jud", "jud_var", "fdi", "veto", "exec", "speech", "cs", "nhri", "regionalcount", "physint_var", "gdp", "elections", "popmillions", "cwar", "physint", "N")

## Name the JAGS parameters

echrjud.params <- c("alpha", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b1.0", "b1.1", "b1.2", "b1.3", "b1.4", "tau")

#Specify intial values (taken from linear regression in Stata)

echrjud.inits1 <- list("alpha[id]"= -.5, "b1"= -.5, "b2"= -.5, "b3"= -.5, "b4"= -.5, "b5" = -.5, "b6"=-.5, "b7"= -.5, "b8"= -.5, "b9" = -.5, "b1.0" = -.5, "b1.1" = -.5, "b1.2" = -.5, "b1.3" = -.5, "b1.4" = -.5)
echrjud.inits2 <- list("alpha[id]"= .5, "b1"= .5, "b2"= .5, "b3"= .5, "b4"= .5, "b5" = .5, "b6"= .5, "b7"= .5, "b8"= .5, "b9" = .5, "b1.0" = .5, "b1.1" = .5, "b1.2" = .5, "b1.3" = .5, "b1.4" = .5)
echrjud.inits <- list(echrjud.inits1, echrjud.inits2)

echrjudfit <- jags(data=echrjud.data, inits=echrjud.inits,
                   parameters=echrjud.params, n.chains=2, n.iter=100000, n.burnin=20000,
                   model.file="BayesECtHRjudiciary.jags")

echrjudfit.upd <- update(echrjudfit, n.iter=200000)



###Diagnostics####
library(mcmcplots)
echrjudfit.mcmc <- as.mcmc(echrjudfit.upd)

traplot(echrjudfit.mcmc, parms = c("b1", "b2", "b3"), style = "plain", main = NULL, col = c("red", "black"))
denplot(echrjudfit.mcmc, parms = c("b1", "b2", "b3"), style = "plain", main = NULL, col = c("red", "black"))

caterplot(echrjudfit.mcmc, parms = c("b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b1.0", "b1.1", "b1.2", "b1.3", "b1.4"), labels = c("IACtHR*Jud", "IACtHR", "Jud", "ExecElec", "Access", "Checks", "Speech", "CS", "NHRI", "Democracy", "GDP (logged)", "Population (logged)", "CWar", "Regional"),
          title("", xlab = "Parameter Estimates"), quantiles = list(outer=c(0.05, 0.95), inner=c(0.05, 0.95)), style = "plain", abline(v = 0, lty = 2), pch = 19)

jagechrjud <- print(echrjudfit.upd, intervals=c(0.025, 0.05, 0.95, 0.975))